
/* enable strict mode */
"use strict";

// define redips object container
window.TSorter = (function(){
//	
	var __bind = function(fn, me) {
		return function() {
			return fn.apply(me, arguments);
		};
	};
	TSorter.prototype.defaults = {
		contSelector:".table",
		itemSelector: ".cell",
        rowBodySelector: ".row_body",
        rowHeadSelector: ".row_header",
        itemPlaceHolder: "<li class='cell'></li>",
        rowPlaceHolder: "<div class='row trip-area-have2-row'></div>"
	};
	function TSorter (opt,map){
		var s = this;
		this.setting = $.extend({},s.defaults,opt);
		
		var dragger = $(this.setting.contSelector).tablesort(this.setting);
		this.dragger = dragger;
		this.selectedRow = null;

		//绑定行的点击事件
		dragger.bindForRow("click",__bind(this.rowClicked2,this)).bindForRow("dropEnd",__bind(this.dropRow,this));

		dragger.bindForCells("dragStart",__bind(this.dragCell,this)).bindForCells("dropEnd",__bind(this.dropCell,this));
//	
		this.changed = false;
		this.map = map;
		//默认触发第一个
		this.rowClicked2(dragger,dragger.getRow(0));
	}
	
	TSorter.prototype.dragCell = function (dragger,cell){
		//验证该行之中必须要有多个地点
		if (cell.getMoveItem().siblings().length == 0){
			alert("每天必须要有一个地点");
			return false;
		}
		//记录当前单元的所在的row
		var row = dragger.findRow(cell);
		cell.from = row;
		return true;
	};
	
	TSorter.prototype.dropCell = function (dragger,cell){
		//如果当前被选中的行，是否有增加或移动元素，需要同步刷新地图
		var curRow = dragger.findRow(cell);
		var sRow = this.selectedRow;
		if (curRow == sRow || cell.from == sRow){
			this.refreshRowMap(sRow);
		}
		this.changed = true;
	};
	
	TSorter.prototype.dropRow = function (dragger,row){
		$(this.setting.contSelector).find(this.setting.rowHeadSelector).each(function(index,item){
			$(this).text("第"+(index+1)+"天");
		});
	
		if (this.selectedRow == row){
			this.map.refreshDayTitle(row.getMoveItem().index()+1);
		}
		this.changed = true;
	};
	
	TSorter.prototype.rowClicked2 = function(dragger,row){
		//1.移除上次选中的行
		var selectedRow = this.selectedRow;
		var _t = this;
		if (selectedRow){
			var moveItem = selectedRow.getMoveItem();
			//移除高亮
			moveItem.removeClass("selected");
			//禁用拖拽
			selectedRow.enableDrag(false);
			//重新绑定点击事件
			var dragItem = selectedRow.getDragItem();
			dragItem.bind("click", function() {
				(__bind(_t.rowClicked2,_t))(dragger,selectedRow);
			});
			
			//记录当天的描述
			var curDesc = $("#dayDesc").val();
			var origDesc = moveItem.attr("trip-day-desc");
			if (curDesc != origDesc){
				moveItem.attr("trip-day-desc",curDesc);
				this.changed = true;
			}
		}
		
		//2.设置当前行未选中行,并且高亮选中框
		this.selectedRow = row;
		//添加高亮
		row.getMoveItem().addClass("selected");
		//设置移动
		row.enableDrag(true);
		//移除点击事件，避免重复刷新地图等。
		row.getDragItem().unbind("click");
		//3.刷新地图，刷新地图列表
		this.refreshRowMap(row);
	};
	
	TSorter.prototype.refreshRowMap = function(row){
		if (!row){
			row = this.selectedRow;
		}
		//记录当前行的数据size
		if (this.map){
			var data = this.getRowData(row);
			this.map.refresh(data);
		}
	};
	
	TSorter.prototype.getRow = function(dragItem){
		return this.dragger.getRowByDragItem(dragItem);
	} ;
	TSorter.prototype.getTableData = function(){
		var days = [];
		var items = [];
		var dests = [];
		var destId;
		var selectedRow = this.selectedRow;
		var s = this;
		$(this.setting.contSelector).find(this.setting.rowHeadSelector).each(function (index){
			var row = s.getRow($(this));
			var moveItem = row.getMoveItem();
			var day = {
					tripDayId:moveItem.attr("trip-day-id"),
					tripDay:(index + 1),
					tripDayDesc:moveItem.attr("trip-day-desc")
			};
			//如果是当前选中的行，需要获取最新的描述
			if (selectedRow == row){
				var curDesc = $("#dayDesc").val();
				if (curDesc != day.tripDayDesc){
					day.tripDayDesc = curDesc;
					s.changed = true;
				}
			}
			//
			days.push(day);
			
			moveItem.find(s.setting.itemSelector).each(function(index){
				//items.push(s.getCellData($(this)));
				var $i = $(this);
				if (!destId){
					destId = $i.attr("trip-dest-id");
				}
				var destName = $i.attr("trip-dest");
				if ($.inArray(destName,dests)== -1){
					dests.push(destName);
				}
				var item = {
						tripItemId:$i.attr("trip-item-id"),
						tripDayId:day.tripDayId,
						tripItemOrder:(index+1),
						lat:$i.attr("trip-lat"),
						lng:$i.attr("trip-lng")
				};
				items.push(item);
			});
		});
		
		var tripName = dests.join("-")+days.length+"日游";
		var tripDistance = 0;
		$.each(items,function(index,item){
			if ((index + 1) < items.length){
				var n = items[index + 1];
				var d = Distance.calcDistance(item.lat,item.lng,n.lat,n.lng);
				if (isNaN(d)){
					d = 0;
				}
				tripDistance += d;
			}
		});
		tripDistance = Distance.round(tripDistance,0);
		if (s.changed){
			return {changed:true,dayCount:days.length,tripDays:days,tripItems:items,destId:destId,tripName:tripName,tripDistance:tripDistance};
		}else{
			return {changed:false,destId:destId,tripName:tripName,tripDistance:tripDistance,dayCount:days.length};
		}
	};
	
	TSorter.prototype.getRowData = function(row){
		//第几天
		var moveItem = row.getMoveItem();
		var day = moveItem.index() + 1;
		//上一天的最后一个地点
		var preDayLast;
		if (moveItem.prev().length != 0){
			var preLastCell = moveItem.prev().find(this.setting.itemSelector).last();
			preDayLast = this.getCellData(preLastCell);
		}
		var items = [];
		var s = this;
		moveItem.find(this.setting.itemSelector).each(function(index){
			items.push(s.getCellData($(this)));
		});
		return {day:day,preDayLast:preDayLast,items:items,dayDesc:moveItem.attr("trip-day-desc")};
	};
	

	TSorter.prototype.getCellData = function($c) {
		return {
			itemId : $c.attr("trip-item-id"),
			img : $c.attr("trip-img"),
			summary : $c.attr("trip-summary"),
			title : $c.attr("trip-title"),
			dest : $c.attr("trip-dest"),
			categoryImg : $c.attr("trip-category-img"),
			categoryId : $c.attr("trip-category-id"),
			stayTime : $c.attr("trip-stay-time"),
			lat : $c.attr("trip-lat"),
			lng : $c.attr("trip-lng")
		};
	};
	return TSorter;
})();

window.TMap = (function (){
	TMap.prototype.setting = {walkkRange:0.5,walkSpeed:0.05,carSpeed:1,
								dayTitle:".trip-area-step3-info-title",
								dayMap:".trip-area-step3-info-map",
								destTitle:".step3-info-title",
								dayItems:".step3-info-l",
								cpath:"",
								refreshAfter:null,
								editable:true};
	function TMap(opt){
		this.setting = $.extend({}, this.setting, opt);
	}
	
	/**
	 * 刷新当天行程的地图
	 */
	TMap.prototype.refresh = function(data){
		//return {day:day,preDayLast:preDayLast,items:items};
		//1.刷新当天的行程的基础信息
		this.refresDayBaseInfo(data);
		//3.刷新地图
		this.refreshMap(data);
		//4.刷新详细列表
		this.refreshItems(data);
		var fn = this.setting.refreshAfter;
		if (fn && typeof fn == 'function'){
			fn.call(this);
		}
	};
	
	/**
	 * 刷新当天行程的地图
	 */
	TMap.prototype.refreshWithoutMap = function(data){
		//1.刷新当天的行程的基础信息
		this.refresDayBaseInfo(data);
		//4.刷新详细列表
		this.refreshItems(data);
	};
	
	TMap.prototype.refresDayBaseInfo = function(data){
		//1.刷新标题
		this.refreshDayTitle(data.day);
		//2.刷新目的地
		var dests = Trip.encapTripDayDests(data);
		var cpath = this.setting.cpath;
		var $pimg = $("<img>").attr("src",cpath+"/resources/portal/img/trip/p.png");
		$(this.setting.destTitle).empty().append($pimg)
						.append("&nbsp;"+dests.join(" "));
		
		$(".step3-info-title2 .infoa").text(data.items.length + "地点");
		
	};
	
	TMap.prototype.refreshMap = function (data){
		//return {day:day,preDayLast:preDayLast,items:items};
		if (!this.map){
			var mapOptions = {
	   				zoom:12,
	   				//center: centerLatLng,
	   				//disableDefaultUI: true,
	   				scrollwheel:false,
	   				mapTypeId: google.maps.MapTypeId.ROADMAP
	   		};
			this.markers = [];
			this.lines = [];
			this.map = new google.maps.Map($(this.setting.dayMap)[0],mapOptions); 
		}
		this.clearMapMarkers();
		this.clearMapLines();
		this.markers = [];
		this.lines = [];
	 	var bounds = new google.maps.LatLngBounds();
	 	var tm = this;
	 	$.each(data.items,function(index,item){
	 		var mk = tm.createMaker(index+1, item);
	 		bounds.extend(mk.getPosition());
	 		tm.markers.push(mk);
	 		if (index > 0){
	 			var line = tm.createLine(tm.markers[index -1], mk);
	 			tm.lines.push(line);
	 		}
	 	});
     
	 	this.map.setCenter(bounds.getCenter());
     	this.map.fitBounds(bounds);
	};
	
	TMap.prototype.refreshDayTitle = function(day){
		$(this.setting.dayTitle).text("第" +day+"天");
	};
	
	TMap.prototype.refreshItems = function (data){
		var totalDistance = 0,totalTime = 0,itemCount = data.items.length;
		//return {day:day,preDayLast:preDayLast,items:items};
		//如果上一天的最后一个地点是酒店，则
		if (data.preDayLast && data.preDayLast.categoryId == 3){
			//firstItem = data.preDayLast;
			data.preDayLast.pre = true;
			data.preDayLast.stayTime = 0;
			data.items.unshift(data.preDayLast);
		}
		
		//计算行程的基础信息,目的地，交通方式，距离，时间等
		Trip.calcTripDayBaseInfo(data);
		$(".step3-info-title2 .infob").text(data.tripDayDistance + "公里");
		//刷新总时间
		$(".step3-info-title2 .infoc").text(data.tripDayTime + "分钟");
		
		//渲染视图
		var $itemlist = $(this.setting.dayItems);
		$itemlist.html("");//清空原来的
		
		//渲染每天行程的地点列表
		Trip.renderTripDayItems(data, $itemlist, this.setting.cpath);
		
		$itemlist.append($("<div>").addClass("clear1"));
		
		//行程描述
		$(".step3-info-info").html("");
		if (this.setting.editable){
			var $edit_img = _create_edit_icon.call(this);
			$(".step3-info-info").append($edit_img).append("每日行程日志");
		}
		
		$(".step3-info-info").append(_create_editor(data.dayDesc));
		//$itemlist.append($desc);
		
	};
	
	function _create_edit_icon (){
		return $("<img>").attr("src",this.setting.cpath+"/resources/portal/img/trip/e.png")
						.click(function(){
							$(this).next().removeAttr("disabled");
						});
	};
	
	function _create_editor(desc){
		var $te = $("<textarea>").attr("id","dayDesc").attr("disabled",true)
								.attr("cols",130).attr("rows",20).text(desc);
		return $te;
	}
	
	TMap.prototype.clearMapMarkers = function(){
		$.each(this.markers,function(index,element){
			element.setMap(null);
		});
	};
	
	TMap.prototype.clearMapLines = function(){
		$.each(this.lines,function(index,element){
			element.setMap(null);
		});
	};
	
	TMap.prototype.createMaker = function(index,item){
		var m = this.map;
		var latLng =  new google.maps.LatLng(item.lat, item.lng);
		var tm = this;
		var marker = new google.maps.Marker({
			position : latLng,
			map : tm.map,
			title:item.title
		});
		marker.setIcon({
     	 	origin: new google.maps.Point(0, 0),
     		anchor:new google.maps.Point(14,38),
     		size : new google.maps.Size(28,38),
     		url:tm.setting.cpath+"/resources/portal/img/googlemap/"+index+".png"
     	});
		return marker;
	};
	
	TMap.prototype.createLine = function(f,t){
		var lineSymbol = {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW};
		// 添加线
		var m = this.map;
		var line = new google.maps.Polyline({
				  path : [f.getPosition(),t.getPosition()],
				  strokeColor : '#ff8700',
				  strokeOpacity : 1.0,
				  strokeWeight : 2,
				  //icons: [{icon: lineSymbol,offset: '100%'}],
				  map: m
				});
		return line;
	};

	return TMap;
})();

var Trip = {};
Trip.renderTripDayItems = function(data,parent,cpath){
	$.each(data.items,function(index,item){
		var $item = $("<div>").addClass("step3-info-m");
		//时间轴的图标
		var timgName;
		if (data.preDayLast && data.preDayLast.pre){
			if (index == 0){
				timgName = "h.png";
			}else{
				timgName = index+".png";
			}
		}else{
			timgName = (index + 1)+".png";
		}
		//时间轴图标
		var $timg = $("<img>").attr("src",cpath+"/resources/portal/img/trip/point/"+timgName);
		var $timg_container = $("<div>").addClass("step3-info-m-cl").append($timg);
		$item.append($timg_container);
		//地点的图片
		var $img = $("<img>").attr("src",item.img);
		var $img_container = $("<div>").addClass("step3-info-m-img").append($img);
		$item.append($img_container);
		//地点的标题
		var $item_cate_img = $("<img>").attr("src",item.categoryImg);
		var $item_title = $("<div>").addClass("step3-info-m-title").text(item.title).append($item_cate_img);
		$item.append($item_title);
		//停留时间
		if (item.stayTime > 0){
			var $item_stay_time = $("<div>").addClass("step3-info-m-time").text(item.stayTime+"分钟");
			$item.append($item_stay_time);
		}
		//地点的简要描述
		var $item_summary = $("<div>").addClass("step3-info-m-note").text(item.summary);
		$item.append($item_summary);
		//追加到父容器中
		parent.append($item);
		//存在距离
		if (item.distance){
	         var $cal = $("<div>").addClass("step3-info-m-other");
	         var $traffic_img = $("<img>");
	         $traffic_img.attr("src",cpath+item.traffic.icon);
	         //设置一个宽度，避免在计算横线的时候不准确
	         $traffic_img.css("width","18px");
	         //距离
	         var $distance = $("<span>").addClass("otherlength")
	         				.append("距离: ").append($traffic_img).append(" "+item.distance+"km");
	         $cal.append($distance);
	         $cal.append(" ");
	         var $time_img = $("<img>").attr("src",cpath+"/resources/portal/img/trip/time.png");
	         //设置一个宽度，避免在计算横线的时候不准确
	         $time_img.css("width","18px");
	         var $time = $("<span>").addClass("othertime").append($time_img).append(" "+item.time+"分钟");
	         
	         $cal.append($time);
	         
	         $cal.append("<span class='otherline'></span>");
	         //追加到父容器中
	         parent.append($cal);
		}
	});
};

Trip.renderTripDayTimeAxis = function(c){
	c.find(".trip-area-step3-info-list").each(function(){
		var linesheight = $(this).height();
		//详细列表上的时间轴处理
		if (c.hasClass("trippopdetails")){
			$(this).find(".step3-info-lines").css("margin-top","37px").height(linesheight - 50);
		}else{
			$(this).find(".step3-info-lines").height(linesheight - 50 - 78);
		}
		
		$(this).find(".step3-info-m-other").each(function(){
	    	 var lineswith = $(this).width() - 26 - $(this).find(".otherlength").width() - $(this).find(".othertime").width();
	         $(this).find("span.otherline").width(lineswith);
	     });
	});
};

Trip.encapTripDayData = function (tripDay){
	//如果传入的是字符串，则默认是id
	if ($.type(tripDay) == 'string'){
		tripDay = $(".trip-step4-info-days[trip-day-id=" + tripDay + "]");
	}
	//var $day = $(".trip-step4-info-days[trip-day-id=" + tripDayId + "]");
	var $items = tripDay.find(".trip-step4-info-model");
	var items = [];
	$items.each(function(index) {
		var $c = $(this);
		var item = {
			itemId : $c.attr("trip-item-id"),
			img : $c.attr("trip-img"),
			summary : $c.attr("trip-summary"),
			title : $c.attr("trip-title"),
			dest : $c.attr("trip-dest"),
			categoryImg : $c.attr("trip-category-img"),
			categoryId : $c.attr("trip-category-id"),
			stayTime : $c.attr("trip-stay-time"),
			lat : $c.attr("trip-lat"),
			lng : $c.attr("trip-lng")
		};
		items.push(item);
	});
	var day = tripDay.attr("trip-day");
	var data = {
		day : day,
		items : items,
		dayDesc : tripDay.attr("trip-day-desc")
	};
	return data;
};

Trip.encapTripDayDests = function(data){
	var dests = [];
	$.each(data.items,function(index,e){
		if ($.inArray(e.dest,dests) == -1){
			dests.push(e.dest);
		}
	});
	return dests;
};

Trip.calcTripDayBaseInfo = function(data){
	var dests = [];
	var tripDayDistance = 0;
	var tripDayTime = 0;
	var items = data.items;
	$.each(items,function(index,item){
		if ($.inArray(item.dest,dests) == -1){
			dests.push(item.dest);
		}
		if (index + 1<items.length){
			var n = items[index +1];
			//计算距离
			var d = Distance.calcDistance(item.lat,item.lng,n.lat,n.lng);
			if (isNaN(d)){
				d = 0;
			}
			item.distance = Distance.round(d,1);
			tripDayDistance += d;
			var t;
			//根据距离选择交通
			var traffic = Trip.selectTraffic(d);
			item.time = Math.ceil(d / traffic.speed);
			item.traffic = traffic;
			tripDayTime += (item.time + parseFloat(item.stayTime));
		}
	});
	data.dests = dests;
	data.tripDayDistance = Distance.round(tripDayDistance,0);
	data.tripDayTime = tripDayTime;
	return data;
};

Trip.trafficTypes = [{from:0,to:0.5,speed:0.05,icon:"/resources/portal/img/trip/walk.png"},
              {from:0.5,to:500,speed:1,icon:"/resources/portal/img/trip/car.png"},
              {from:500,to:9999999999,speed:12,icon:"/resources/portal/img/trip/plane.png"}];
Trip.selectTraffic = function (d){
	var types = Trip.trafficTypes;
	var type;
	$.each(types,function(index,item){
		if (d > item.from && d <= item.to){
			type = item;
			return false;
		}
	});
	if (!type){
		type = types[types.length -1];
	}
	return type;
};

Trip.layerTripDayOverlook = function(tripDayId,map){
	//抽取当天行程的数据
	var data = Trip.encapTripDayData(tripDayId);
	map.refreshWithoutMap(data);
	$(".popdialog2").show();
	Trip.layer(".popdialog2", function(){
		Trip.renderTripDayTimeAxis($(".popdialog2"));
		map.refreshMap(data);
	});
};
Trip.layer = function(layerSelector,sfn){
	//页面层例一
	$.layer({
		shade : [ 0.5, '#000', true ],
		type : 1,
		fix : false,
		closeBtn : [ 0, true ],
		area : [ 'auto', 'auto' ],
		title : false,
		border : [ 0 ],
		offset : [ '50%', '50%' ],
		page : {
			dom : layerSelector
		},
		close : function(index) {
			layer.close(index);
			// $('.popdialog').show();
		},
		loading : {
			type : 0
		},
		success :sfn
	});
};
Trip.layerTripOverlook = function(cpath){
	var c = $(".trippopdetails");
	//清空原来的数据
	c.html("");
	//封装
	$(".trip-step4-info-days").each(function(index){
		var data = Trip.encapTripDayData($(this));
		//计算每天的行程的基础数据
		Trip.calcTripDayBaseInfo(data);
		var tripDayCont = $("<div class='trip-step4-pop-details'>");
		
		var tripDayTop = $("<div class='trip-step4-pop-details-top'>");
		var tripDayTitle = $("<div class='trip-step4-pop-details-top-title'>");
		var title = "第"+(index+1)+"天 "+data.dests.join(" ");
		tripDayTitle.text(title);
		
		var tripDayTopRight = $("<div class='trip-step4-pop-details-top-o'>");
		//时间
		var time = $("<div class='areatime'>").text(data.tripDayTime+"分钟");
		//距离
		var distance = $("<div class='arealength'>").text(data.tripDayDistance+"KM");
		//地点
		var itemCount = $("<div class='areacount'>").text(data.items.length+"地点");
		//放入顶部左边
		tripDayTopRight.append(time).append(distance).append(itemCount);
		//标题放入到顶部，
		tripDayTop.append(tripDayTitle).append(tripDayTopRight);
		
		//每天行程的列表
		var tripDayListCont = $("<div class='trip-area-step3-info-list'>");
		var tripDayAxis = $(" <div class='step3-info-lines'>");
		var tripDayList = $("<div class='step3-info-l borderbottomnone'>");
		//渲染每个列表
		Trip.renderTripDayItems(data, tripDayList, cpath);
		tripDayList.append("<div class='clear'>");
		
		//下部列表容器
		tripDayListCont.append(tripDayAxis).append(tripDayList);
		
		tripDayCont.append(tripDayTop).append(tripDayListCont);
		
		c.append(tripDayCont);
		c.append("<div class='clear1'>");
	});
	
	Trip.layer(".trippopdetails", function(){
		//map.refreshMap(data);
		Trip.renderTripDayTimeAxis($(".trippopdetails"));
	});
};